from utils.e_mail import sendMail
from worker.base.base_worker import BaseWorker
from utils.log_util import prints, saveLog
from constant.plan_constant import trade_plan
from constant.param_config import getRechangeDate
from constant.globl_constant import earningDict
import datetime
import threading
import time


class StatisticWorker(BaseWorker):

    lastDay = -1

    def __init__(self):
        super().__init__()

    def startThread(self):
        """
        开启交易线程
        """
        thread = threading.Thread(target=self.worker)
        # thread.daemon = True  # 设置线程为守护线程，以便在主程序退出时自动结束线程
        thread.start()

    def worker(self):
        """
        订单统计
        """

        prints("订单统计服务已启动...")

        while True:
            if self.isLogin and self.marketClose() is False:
                timeNow = datetime.datetime.now().day
                dayHour = datetime.datetime.now().hour
                if self.lastDay != timeNow and (self.lastDay == -1
                                                or dayHour == 6):
                    self.analyse()
                    self.lastDay = timeNow
            time.sleep(10 * 60)

    def analyse(self):
        balance = 0
        rechangeDate = getRechangeDate()
        timeNow = datetime.datetime.now()

        earningDict.clear()
        if timeNow > rechangeDate:
            allOrder = self.getLastRechangeOrder()

            if len(allOrder) == 0:
                return

            balance = self.getAccountMoney()

            # 充值日期距今相差天数
            dayOffset = (timeNow - rechangeDate).days
            weekdaysBetween = self.getWeekdaysBetween(rechangeDate, timeNow)

            # 共交易订单数量
            dayOrderSize = len(allOrder)

            # 盈利订单
            positiveOrderList = [item for item in allOrder if item.profit > 0]

            # 亏损订单
            negativeOrderList = [item for item in allOrder if item.profit < 0]

            # 盈利总金额
            positiveAmount = int(
                sum(obj.profit for obj in positiveOrderList) * 100) / 100

            # 亏损总金额
            negativeAmount = int(
                sum(obj.profit for obj in negativeOrderList) * 100) / 100

            # 实际盈利
            reallyProfit = positiveAmount - abs(negativeAmount)

            # 实际交易天数
            count = len(weekdaysBetween)

            earningDict["balance"] = balance
            earningDict["days"] = count
            earningDict["orders"] = dayOrderSize
            earningDict["positive"] = len(positiveOrderList)
            earningDict["negative"] = len(negativeOrderList)
            earningDict["profit"] = positiveAmount
            earningDict["loss"] = negativeAmount
            earningDict["really"] = reallyProfit

            # 期望总金额
            hopeMoney = ""
            if count != 0:
                wishProfit = int(
                    self.expectProfit(balance - reallyProfit, count) *
                    100) / 100
                # 实际总额与期望总额的差值
                diffValue = int((wishProfit - balance) * 100) / 100
                earningDict["unfinish"] = diffValue
                earningDict["hope"] = wishProfit

                moreMoney = "未完成金额为" + str(
                    diffValue) + "美金" if diffValue > 0 else "实现超额盈利" + str(
                        abs(diffValue)) + "美金"
                hopeMoney = "期望总额为" + str(wishProfit) + "美元\n" + moreMoney

            msg = "账户总资产为" + str(balance) + "美金\n已交易" + str(
                count) + "天\n共交易" + str(dayOrderSize) + "单\n盈利" + str(
                    len(positiveOrderList)) + "单\n盈利金额为" + str(
                        positiveAmount) + "美金\n亏损" + str(
                            len(negativeOrderList)) + "单\n亏损金额为" + str(
                                abs(negativeAmount)) + "美金\n实际盈利为" + str(
                                    reallyProfit) + "美金\n" + (
                                        hopeMoney if hopeMoney != "" else "")
            saveLog(msg)
            sendMail("交易统计", msg, timer=False,send=True)

    def expectProfit(self, initial, day):
        """
        计算预期盈利
        """
        for index in range(0, day):
            for index in range(0, len(trade_plan)):
                item = trade_plan[index]
                planDollar = item["initDollar"]
                planLot = item["lot"]
                planProfit = item["profit"]

                if index == 0 and initial <= planDollar:
                    initial = initial + planLot * 100 * planProfit
                    break

                if index == len(trade_plan) - 1 and initial >= planDollar:
                    initial = initial + planLot * 100 * planProfit
                    break

                nextDollar = trade_plan[index + 1]["initDollar"]
                if initial >= planDollar and initial <= nextDollar:
                    initial = initial + planLot * 100 * planProfit
                    break
        return initial

    def getWeekdaysBetween(self, datetime1, datetime2):
        current_date = datetime1
        result = []
        while current_date <= datetime2:
            if current_date.weekday() < 5:  # 0代表周一，5代表周六，6代表周日
                result.append(current_date)
            current_date += datetime.timedelta(days=1)
        return result
